package elven.codingit.easysearch.util;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.FSDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 索引写入对象
 * @author liuyy
 * @date 2016年8月26日
 */
public class IndexerWrite {

	private static final Logger log = LoggerFactory.getLogger(IndexerWrite.class);
	
	/**
	 * 写入文件到paoword
	 * @param list
	 * @author liuyy
	 * @date 2016年8月30日
	 */
	public int writeApp(List<Map<String, Object>> list){
		try {
			return write(list, IndexHelper.getInstance().openPaowordDirectory());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return 0;
		}
	}
	
	/**
	 * @param list
	 * @param directory
	 * @return
	 * @author liuyy
	 * @date 2016年9月6日
	 */
	private int write(List<Map<String, Object>> list, FSDirectory directory){
		IndexWriter indexWriter = null;
		try {
			IndexHelper helper =  IndexHelper.getInstance();
			IndexWriterConfig indexWriterConfig = new IndexWriterConfig(helper.configAnalyzer());
			indexWriterConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
			indexWriter = new IndexWriter(directory, indexWriterConfig);
			log.warn("lucene索引写入API是否已打开 : {}",indexWriter.isOpen());
			log.warn("要写入的数量 : {}",list.size());
			for(int i = 0;i < list.size(); i++){
				Map<String, Object> maps = (Map<String, Object>) list.get(i);
				indexWriter.deleteDocuments(new Term("id", String.valueOf(maps.get("id"))));
				Document idoc = new Document();
				for(String key : maps.keySet()){
					idoc.add(helper.getDataField(maps.get(key), key));
				}
				indexWriter.addDocument(idoc);
				if(i != 0 && i % 1000 == 0){
					log.warn("start commit... index for {}", i+1);
					indexWriter.commit();
					log.warn("end commit...");
				}else if(i != 0 && i+1 == list.size()){
					log.warn("start commit... index for {}", i+1);
					indexWriter.commit();
					log.warn("end commit...");
				}
			}
			indexWriter.close();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return 0;
		} finally{
			try {
				indexWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return list.size();
	}
	
}
